<?php
namespace daswork;

use daswork\Config;
use daswork\db\Mysql;

class Model
{
	// 查询次数
	public static $queryTimes = 0;
	// 执行次数
	public static $executeTimes = 0;	
    // 数据库连接参数配置
    protected $connection = [];
	// 数据库查询对象池
	protected static $links = [];
	// 当前类名称
	protected $class;
	// 当前模型名称
	protected $name;
	// 当前查询对象
    protected $query;
    // 当前数据表名称（含前缀）
    protected $tablename = '';
    // 当前数据表名称（不含前缀）
    protected $table = '';
    // 当前数据表主键
    protected $pk;
    // 当前数据表前缀
    protected $prefix = '';
    // 查询参数
    protected $options = [];
    // 最近查询的 sql 语句
    public $sql = '';
	/**
     * 初始化过的模型.
     *
     * @var array
     */
    protected static $initialized = [];

	public function __construct()
	{
		// 当前类名
		$this->class = get_called_class();

		if (empty($this->name)) {
			// 当前模型名
			$name = str_replace('\\', '/', $this->class);
			$this->name = basename($name);
        }
        
        // 合并数据库配置
        if (!empty($this->connection) && is_array($this->connection)) {
            $connection = array_merge(Config::get('db'), $this->connection);
        } else {
            $connection = Config::get('db');
        }
    
        $this->connection = $connection;

        // 设置当前数据表和模型名
        if (isset($connection['prefix'])) {
            $this->prefix = $connection['prefix'];
        }
        if (!empty($this->table)) {
            $this->tablename = $this->prefix .  $this->table;
        } else {
            $this->tablename = $this->prefix . uncamelize($this->name);
        }

		// 执行初始化操作
		$this->initialize();
    }
    
    /**
     *  初始化模型
     * @access protected
     * @return void
     */
    protected function initialize()
    {
        $class = get_class($this);
        if (!isset(static::$initialized[$class])) {
            static::$initialized[$class] = true;
            static::init();
        }
	}
	
	/**
     * 初始化处理
     * @access protected
     * @return void
     */
    protected static function init()
    {
    }

    /**
     * 获取当前模型的查询对象
     * @access public
     * @param bool      $buildNewQuery  创建新的查询对象
     * @return Query
     */
    public function getQuery($buildNewQuery = false)
    {
        if ($buildNewQuery) {
            return Mysql::connect($this->connection);
        } elseif (!isset(self::$links[$this->class])) {
            // 创建模型查询对象
            self::$links[$this->class] = Mysql::connect($this->connection);
        }

        return self::$links[$this->class];
    }

    /**
     * 指定默认数据表名（含前缀）
     * @access public
     * @param string $table 表名
     * @return $this
     */
    public function setTablename($tablename)
    {
        $this->tablename = $tablename;
    }

    /**
     * 得到当前或者指定名称的数据表
     * @access public
     * @param string $name
     * @return string
     */
    public function getTablename()
    {
        return $this->tablename;
    }

	/**
     * 执行sql
     * @param string $sql
     * @return mixd $res
     */
    public function exec($sql)
    {
        @$res = $this->getQuery()->exec($sql);
        $this->$sql = $sql;
        return $res;
    }

    public function query($sql)
    {
        $result = $this->getQuery()->query($sql);
        $this->$sql = $sql;
        return $result;
    }
    
    public function lastInsertRowID ()
    {
        $result = $this->getQuery()->lastInsertRowID();
        return $result;
    }

    public function lastErrorMsg()
    {
        return $this->getQuery()->lastErrorMsg();
    }

    /**
     * 查询数组列表
     */
    public function select($sql)
    {
        $result = $this->getQuery()->query($sql);
        $data = array();
        while ($arr = $result->fetch_assoc()) {
            $data[] = $arr;
        }
        return $data;
    }

    /**
     * 列表结果集
     */
    public function list($where='')
    {
        $sql = "select * from $this->tablename $where;";
        return $this->select($sql);
    }

    /**
     * 查询一条
     */
    public function getOneById($id, $tablename='')
    {
        $tablename = $tablename ? $tablename : $this->tablename;
        $sql = "SELECT * FROM `$tablename` WHERE `id`=$id;";
        $result = $this->getQuery()->query($sql);
        // var_dump($result);
        $data = $result->fetch_all(MYSQLI_ASSOC);
        // var_dump($data);
        return $data;
    }

    /**
     * 单列合计
     */
    public function sumColumn($column, $tablename)
    {
        $tablename = $tablename ? $tablename : $this->tablename;
        $sql = "SELECT sum(`$column`) as sumData FROM `$tablename`;";
        $result = $this->getQuery()->query($sql);
        // $data = $result->fetch_assoc();
        // var_dump($data['sumData']);exit;
        if ($data = $result->fetch_assoc()) {
            return $data['sumData'];
        }
        return 0;
    }

    public function listByName($name='', $order = '', $desc = false)
    {
        $where = "";
        if ($name) {
            $where = " where name like '%$name%'";
        }

        if ($order) {
            $where .= " order by $order";
            if ($desc) {
                $where .= " desc";
            } else {
                $where .= " asc";
            }
        }
        $sql = "select * from $this->tablename $where;";
        $res = $this->select($sql);

        return $res;
    }

    /**
     * save
     */
    public function save($data)
    {
        $columns = "";
        $values = "";
        foreach ($data as $key => $value) {
            $columns .=  "`" . $key . "`,";
            $values .=  "'" . $value . "',";
        }
        $columns = rtrim($columns, ',');
        $values = rtrim($values, ',');
        $sql = "INSERT INTO `$this->tablename`(" . $columns . ") VALUES(". $values . ");";
        return $this->exec($sql);
    }
    
    /**
     * updateById
     */
    public function updateById($data)
    {
        $id = $data['id'];
        unset($data['id']);
        $columns = "";
        foreach ($data as $key => $value) {
            $columns .= "`" . $key . "`='" . $value ."',";
        }
        $columns = rtrim($columns, ',');
        $sql = "UPDATE `$this->tablename` SET $columns WHERE `id`=$id";
        return $this->exec($sql);
    }

    /**
     * deleteByIds
     */
    public function deleteById($id)
    {
        $sql = "DELETE FROM `$this->tablename` WHERE `id` IN(";
        if (is_array($id)) {
            for ($i=0; $i < count($id); $i++) { 
                $sql .= $id[$i] . ',';
            }
            $sql = rtrim($sql, ',');
            $sql .= ");";
        } else {
            $sql = "DELETE FROM `$this->tablename` WHERE `id`=$id;";
        }
        return $this->exec($sql);
    }

    // public function __destruct()
    // {
    //     $this->query->close();
    // }


	function add($data){
		
		//列名数组
		$cols=array();
		//列值数组
		$vals=array();
		
		foreach($data as $key=>$val){
			$cols[]="`".$key."`"; 
			$vals[]="'".$val."'";
		}
		
		//$cols=array(0=>'`titlekey`',1=>'`contentkey`'); //
		//$vals=array(0=>"'titleval'",1=>"'contentval'"); //
		
		
		//用","将数组每个元素重新拼接起来
		$str_cols=implode(',',$cols);  //$str_cols=  `titlekey`,`contentkey` 
		$str_vals=implode(',',$vals);  //$str_vals=  'titleval','contentval'
		
		//执行插入数据
		$sql="insert into ".$this->tablename."($str_cols) values($str_vals);";
		
		return $this->getQuery()->insert($sql );
	}
	
	
	function update($data,$where){
		
		
		$wherestr = '';
		if(!empty($where)){
			$wherestr .=' where '.$where;
		}
		
		$par_array=array();
		foreach($data as $key=>$val){
			$par_array[]="`".$key."`="."'".$val."'";
		}
		
		//用","将修改列和列值的数组里每个元素重新拼接起来
		$param=implode(',',$par_array); 
			
		$sql = "update ".$this->tablename." set ".$param." ".$wherestr." ";
		
		return $this->getQuery()->query($sql);
		
	}
	
	function get_lists($where, $limit=''){
		
		$wherestr = '';
		if(!empty($where)){
			$wherestr .=' where '.$where;
		}
		$sql = 'select * from '.$this->tablename.$wherestr . $limit;
//		echo $sql;
		return $this->getQuery()->select($sql);
	}

	function get_sum($where){
		$wherestr = '';
		if(!empty($where)){
			$wherestr .=' where '.$where;
		}
		
		$sql = "select count(*) as sum from ".$this->tablename.$wherestr;
		
		$data = $this->getQuery()->get_row($sql);
		
		return $data['sum'];
	}
	
	
	
	function get_one($where){
		
		$wherestr = '';
		if(!empty($where)){
			$wherestr .=' where '.$where;
		}
		
		$sql = "select * from ".$this->tablename.$wherestr;
		
		//var_dump($sql);exit;
		
		$data = $this->getQuery()->get_row($sql);
		
		return $data;
	}
}